<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;

include_once dirname(__FILE__) . '/phpmailer/src/PHPMailer.php';
include_once dirname(__FILE__) . '/phpmailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
/**
 * Email
 * 
 * @package Email
 * @author yaecho
 * @version 1.0.0
 * @link http://yaecho.net
 */
class Email_Plugin implements Typecho_Plugin_Interface
{
    // 是否启用
    const ENABLE_YES = 1;  //启用
    const ENABLE_NO = 0;  //不启用

    //备份周期
    const BACKUP_TIME = array(
        'day' => 84600,
        'week' => 604800,
        'month' => 2592000,
    );

    /**
     * 激活插件方法,如果激活失败,直接抛出异常
     * 
     * @access public
     * @return void
     * @throws Typecho_Plugin_Exception
     */
    public static function activate()
    {
        //注册登录失败提醒
        Typecho_Plugin::factory('Widget_Login')->loginFail = array('Email_Plugin', 'warn');
        //注册登录成功数据备份功能
        Typecho_Plugin::factory('Widget_Login')->loginSucceed = array('Email_Plugin', 'backup');
        //注册留言提醒
        Typecho_Plugin::factory('Widget_Feedback')->finishComment = array('Email_Plugin', 'commentRemind');
        //数据库增加备份时间字段
        $db = Typecho_Db::get();
        $result = $db->query($db->insert('table.options')->rows(array('name' => 'lastBackupTime', 'user' => 0, 'value' => time())));
    }
    
    /**
     * 禁用插件方法,如果禁用失败,直接抛出异常
     * 
     * @static
     * @access public
     * @return void
     * @throws Typecho_Plugin_Exception
     */
    public static function deactivate(){
        //数据库删除备份时间字段
        $db = Typecho_Db::get();
        $result = $db->query($db->delete('table.options')->where('name = ?', 'lastBackupTime'));
    }
    
    /**
     * 获取插件配置面板
     * 
     * @access public
     * @param Typecho_Widget_Helper_Form $form 配置面板
     * @return void
     */
    public static function config(Typecho_Widget_Helper_Form $form)
    {
        //是否开启登录报警
        $loginWarn = new Typecho_Widget_Helper_Form_Element_Radio('loginWarn', array(
            self::ENABLE_YES   =>  _t('启用'),
            self::ENABLE_NO   =>  _t('不启用')
        ), self::ENABLE_NO, _t('是否启用登录报警'));
        $form->addInput($loginWarn->addRule('enum', _t('必须选择一个'), array(self::ENABLE_YES, self::ENABLE_NO)));
        //数据备份
        $backupTime= new Typecho_Widget_Helper_Form_Element_Radio(
            'backupTime',
            array('day' => _t('每天'), 'week' => _t('每周'), 'month' => _t('每月'), 'shutdown' => _t('关闭')),
            'shutdown',
            _t('备份周期')
        );
        $form->addInput($backupTime->addRule('enum', _t('必须选择一个'), array('day', 'week', 'month', 'shutdown')));
        //留言提醒
        $commentRemind = new Typecho_Widget_Helper_Form_Element_Radio('commentRemind', array(
            self::ENABLE_YES   =>  _t('启用'),
            self::ENABLE_NO   =>  _t('不启用')
        ), self::ENABLE_NO, _t('是否启用留言提醒'));
        $form->addInput($commentRemind->addRule('enum', _t('必须选择一个'), array(self::ENABLE_YES, self::ENABLE_NO)));
        //smtp
        $host = new Typecho_Widget_Helper_Form_Element_Text('host', NULL, 'smtp.example.com', _t('SMTP服务器'));
        $form->addInput($host->addRule('required', _t('必须填写一个SMTP服务器地址')));
        //port
        $port = new Typecho_Widget_Helper_Form_Element_Text('port', NULL, '994', _t('SMTP端口'));
        $form->addInput($port->addRule('required', _t('必须填写一个SMTP端口')));
        //username
        $username = new Typecho_Widget_Helper_Form_Element_Text('username', NULL, 'admin@website.com', _t('发信邮箱'));
        $form->addInput($username->addRule('required', _t('必须填写一个发信邮箱')));
        //password
        $password = new Typecho_Widget_Helper_Form_Element_Text('password', NULL, 'password', _t('密码'));
        $form->addInput($password->addRule('required', _t('必须填写一个密码')));
        //backup email
        $b_email = new Typecho_Widget_Helper_Form_Element_Text('b_email', NULL, 'backup@website.com', _t('收信邮箱'));
        $form->addInput($b_email->addRule('required', _t('必须填写一个收信邮箱')));
    }
    
    /**
     * 个人用户的配置面板
     * 
     * @access public
     * @param Typecho_Widget_Helper_Form $form
     * @return void
     */
    public static function personalConfig(Typecho_Widget_Helper_Form $form){}

    /**
     * 登录失败报警
     * 
     * @access public
     * @param object $user
     * @param string $name
     * @param string $password
     * @return void
     */
    public static function warn($user, $name, $password)
    {
        $enable = Typecho_Widget::widget('Widget_Options')->plugin('Email')->loginWarn;
        // 是否启用
        if ($enable != self::ENABLE_YES) {
            return;
        }
        $receiver = htmlspecialchars(Typecho_Widget::widget('Widget_Options')->plugin('Email')->b_email);
        $subject = '异常登录告警';
        $content = "登录失败，记录如下<br>username: {$name} Password: {$password}<br>IP: {$_SERVER["REMOTE_ADDR"]}";
        register_shutdown_function('Email_Plugin::send' , $receiver, $subject, $content);
    }

    /**
     * 备份
     *
     * @return void
     */
    public static function backup()
    {
        $type = Typecho_Widget::widget('Widget_Options')->plugin('Email')->backupTime;
        // 是否启用
        if ($type == 'shutdown') {
            return;
        }
        //判断时间
        $db = Typecho_Db::get();
        $lastBackupTime = $db->fetchRow($db->select('value')->from('table.options')->where('name = ?', 'lastBackupTime'));
        $nowTime = time();
        if (($nowTime - $lastBackupTime['value']) < self::BACKUP_TIME[$type]) {
            return;
        }
        //更新上次备份时间
        $db->query($db->update('table.options')
        ->rows(array('value' => $nowTime))
        ->where('name = ?', 'lastBackupTime'));

        register_shutdown_function('Email_Plugin::backupTask');
    }

    /**
     * 评论提醒
     *
     * @param object $comment
     * @return void
     */
    public static function commentRemind($comment)
    {
        $enable = Typecho_Widget::widget('Widget_Options')->plugin('Email')->commentRemind;
        // 是否启用
        if ($enable != self::ENABLE_YES) {
            return;
        }
        //检查留言者是否为管理员
        $db = Typecho_Db::get();
        $admin = $db->fetchAll($db->select('uid')->from('table.users')->where('group = ?', 'administrator'));
        $admin_uid = array_column($admin, 'uid');
        if(in_array($comment->authorId, $admin_uid)) {
            return;
        }

        $receiver = htmlspecialchars(Typecho_Widget::widget('Widget_Options')->plugin('Email')->b_email);
        $subject = '博客有新的留言';
        $commentCreated = date('Y-m-d H:i:s', $comment->created);
        $content = "{$comment->author} 在 {$comment->title} 留言<br>留言内容：{$comment->text}<br>时间：{$commentCreated}";
        register_shutdown_function('Email_Plugin::send' , $receiver, $subject, $content);
    }

    /**
     * 备份任务
     *
     * @return void
     */
    public static function backupTask()
    {
        include_once dirname(__FILE__) . '/BackUpToJson.php';
        $BackUp = new BackUpToJson();
        $file = $BackUp->write();
        if ($file !== false) {
            $receiver = htmlspecialchars(Typecho_Widget::widget('Widget_Options')->plugin('Email')->b_email);
            $subject = '博客数据备份';
            $content = date('Y-m-d_H:i:s', time());
            $attach = array($content . '_data.zip' => $file);
            self::send($receiver, $subject, $content, $attach);
            $BackUp->clean();
        }
    }

    /**
     * 邮件发送
     *
     * @param string/array $receiver
     * @param string $subject
     * @param string $content
     * @param string/array $file
     * @return void
     */
    public static function send($receiver, $subject, $content, $file = null)
    {
        // get email name
        $emailName = htmlspecialchars(Typecho_Widget::widget('Widget_Options')->plugin('Email')->username);
        //实例化
        $mail = new PHPMailer();
        // set charset
        $mail->CharSet='utf-8';
        // set encode
        $mail->Encoding = "base64";
        // Enable verbose debug output
        $mail->SMTPDebug = 0;
        // Set mailer to use SMTP
        $mail->isSMTP();
        // Specify main and backup SMTP servers
        $mail->Host = htmlspecialchars(Typecho_Widget::widget('Widget_Options')->plugin('Email')->host);
        // Enable SMTP authentication
        $mail->SMTPAuth = true;
        // SMTP username
        $mail->Username = $emailName;
        // SMTP password
        $mail->Password = htmlspecialchars(Typecho_Widget::widget('Widget_Options')->plugin('Email')->password);
        // Enable TLS encryption, `ssl` also accepted
        $mail->SMTPSecure = 'ssl';
        // TCP port to connect to
        $mail->Port = htmlspecialchars(Typecho_Widget::widget('Widget_Options')->plugin('Email')->port);
    
        //Recipients
        $mail->setFrom($emailName, 'Yaecho site');
        if (is_array($receiver)) {
            foreach($receiver as $one) {
                $mail->addAddress($one);
            }
        } else {
            $mail->addAddress($receiver);
        }
    
        //Attachments
        if (!is_null($file)) {
            if (is_array($file)) {
                foreach ($file as $name => $single) {
                    if (is_numeric($name)) {
                        // Add attachments
                        $mail->addAttachment($single);
                    } else {
                        // Optional name
                        $mail->addAttachment($single, $name);
                    }
                }
            } else {
                $mail->addAttachment($file);
            }
        }
    
        //Content
        $mail->isHTML(true);// Set email format to HTML
        $mail->Subject = $subject;
        $mail->Body    = $content;
    
        $mail->send();
    }
    
}